import {
	apiUrl,
} from '../config'
import {
	token,
	userInfo
} from '../utils/token'
import {
	formatGetUri
} from '../utils/util.js'


const request = {}


request.globalRequest = (url, method, params, showLoading = true) => {
	const headers = {
		'Content-Type': 'application/json'
	}
	console.log(params)
	headers["X-Access-Token"] = token.get() ? token.get() : ''
	if (showLoading) {
		uni.showLoading({
			title: '加载中'
		});
	}
	const body = params.data ? params.data : {}

	return uni.request({
		url: apiUrl + url + formatGetUri(params.params),
		method,
		data: body,
		dataType: 'json',
		header: headers
	}).then(res => {
		if (showLoading) {
			uni.hideLoading();
		}

		if (res[1]) {
			console.log(res[1])
			const {
				statusCode,
				data
			} = res[1]
			if (statusCode == 200) {
				if (data.code != 200 && data.code != 0) {
					uni.showToast({
						title: data.message,
						icon: 'none'
					})
				}
				return data
			} else if (statusCode == 401) {
				token.clear();
				userInfo.clear()
				// uni.showToast({
				// 	title: data.message,
				// 	icon: 'none'
				// })
				uni.reLaunch({
					url: "/pages/login/login"
				})
			} else {
				throw data
			}
		} else { 
			uni.showToast({
				title: "请求的接口没有响应",
				icon: 'none'
			})
			throw data
		}

	}).catch(err => {

		if (showLoading) {
			uni.hideLoading();
		}

		// console.log(err)
		if (err.code == 401) {
			token.clear();
			userInfo.clear()
			uni.reLaunch({
				url: "/pages/login/login"
			})
 
		}

		uni.showToast({
			title: err.message,
			icon: 'none'
		})
		throw err
	})


}


export default request
